package com.supinfo.food.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @desc Classe de serialisation
 * 
 * @projectName : Launcher
 * @author Keitaro
 * 
 */
public class SerialisationTools {
	private static final Logger logger = LoggerFactory.getLogger(SerialisationTools.class);
	static private BASE64Encoder encode = new BASE64Encoder();
	static private BASE64Decoder decode = new BASE64Decoder();

	static public String serialisation(Object obj) {
		String out = null;
		if (obj != null) {
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos);
				oos.writeObject(obj);
				out = encode.encode(baos.toByteArray());
			} catch (IOException e) {
				logger.error("Error IO Exception", e);
			}
		}
		return out;
	}

	static public Object deserialisation(String str) {
		Object out = null;
		if (str != null) {
			try {
				ByteArrayInputStream bios = new ByteArrayInputStream(
						decode.decodeBuffer(str));
				ObjectInputStream ois = new ObjectInputStream(bios);
				out = ois.readObject();
			} catch (IOException e) {
				return null;
			} catch (ClassNotFoundException e) {
				logger.error("Error IO Exception", e);
			}
		}
		return out;
	}
}
